import { editProfile,logout,setupUserProfile} from "./auth.js";
window.editProfile = editProfile;
window.logout = logout;
window.setupUserProfile = setupUserProfile;
document.addEventListener('DOMContentLoaded', async () => {
    const urlParams = new URLSearchParams(window.location.search);
    const username = urlParams.get('username');
    
    if (!username) {
        alert('用户信息缺失，请重新登录');
        window.location.href = 'login.html';
        return;
    }
    await setupUserProfile(username);
    
    
    try {
        // 获取教师信息
        const userResponse = await fetch(`/user-info?username=${username}`);
        const userData = await userResponse.json();
        
        if (userData.role !== '教师') {
            alert('该功能为教师专属');
            window.location.href = 'success.html?username=' + username;
            return;
        }
        
        // 获取教师创建的课程
        const coursesResponse = await fetch(`/get-my-courses`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username })
        });
        const courses = await coursesResponse.json();
        
        // 获取每个课程的助教
        const tutorsByCourse = {};
        for (const course of courses) {
            const tutorsResponse = await fetch(`/get-course-tutors?courseCode=${course.course_code}`);
            const tutors = await tutorsResponse.json();
            tutorsByCourse[course.course_code] = tutors;
        }
        
        renderTutorsTable(courses, tutorsByCourse);
    } catch (error) {
        console.error('获取助教信息失败:', error);
        alert('获取助教信息失败，请稍后重试');
    }
});

function renderTutorsTable(courses, tutorsByCourse) {
    const container = document.getElementById('tutorsContainer');
    container.innerHTML = '';
    
    // 添加助教按钮
    const addButton = document.createElement('button');
    addButton.className = 'btn-add-tutor mb-6';
    addButton.innerHTML = '<i class="fas fa-plus mr-2"></i>添加助教';
    addButton.onclick = openAddTutorModal;
    container.appendChild(addButton);
    
    // 创建表格 - 添加边框样式
    const table = document.createElement('table');
    table.className = 'tutors-table border-collapse border border-gray-200';
    
    // 表头 - 添加边框和背景色
    const thead = document.createElement('thead');
    thead.innerHTML = `
        <tr>
            <th class="table-header border border-gray-300 bg-gray-100">所属课程</th>
            <th class="table-header border border-gray-300 bg-gray-100">助教姓名</th>
            <th class="table-header border border-gray-300 bg-gray-100">助教学号</th>
            <th class="table-header border border-gray-300 bg-gray-100 text-center">操作</th>
        </tr>
    `;
    table.appendChild(thead);
    
    // 表体 - 添加边框和斑马条纹
    const tbody = document.createElement('tbody');
    tbody.id = 'tutorsBody';
    
    let hasTutors = false;
    let rowIndex = 0;
    
    for (const course of courses) {
        const tutors = tutorsByCourse[course.course_code] || [];
        
        if (tutors.length === 0) {
            const row = document.createElement('tr');
            row.className = `no-tutors-row ${rowIndex % 2 === 0 ? 'even-row bg-gray-50' : 'odd-row bg-white'}`;
            row.innerHTML = `
                <td class="table-cell border border-gray-200">${course.course_name}</td>
                <td class="table-cell border border-gray-200" colspan="3">暂无助教</td>
            `;
            tbody.appendChild(row);
            rowIndex++;
        } else {
            hasTutors = true;
            tutors.forEach(tutor => {
                const row = document.createElement('tr');
                row.className = `tutor-row ${rowIndex % 2 === 0 ? 'even-row bg-gray-50' : 'odd-row bg-white'}`;
                row.innerHTML = `
                    <td class="table-cell border border-gray-200">${course.course_name}</td>
                    <td class="table-cell border border-gray-200">${tutor.tutor_name}</td>
                    <td class="table-cell border border-gray-200">${tutor.tutor_student_id}</td>
                    <td class="table-cell border border-gray-200 text-center">
                        <button onclick="removeTutor('${tutor.tutor_id}', this)" 
                            class="btn-remove-tutor">
                            <i class="fas fa-user-minus mr-2"></i>移除
                        </button>
                    </td>
                `;
                tbody.appendChild(row);
                rowIndex++;
            });
        }
    }
    
    if (!hasTutors) {
        const row = document.createElement('tr');
        row.className = 'no-tutors-message bg-gray-50';
        row.innerHTML = `
            <td class="table-cell border border-gray-200 text-center" colspan="4">暂无助教</td>
        `;
        tbody.appendChild(row);
    }
    
    table.appendChild(tbody);
    container.appendChild(table);
}

// 打开添加助教模态框
window.openAddTutorModal = async function() {
    const username = new URLSearchParams(window.location.search).get('username');
    
    try {
        // 获取教师创建的课程
        const response = await fetch(`/get-my-courses`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username })
        });
        const courses = await response.json();
        
        const courseSelect = document.getElementById('courseSelect');
        courseSelect.innerHTML = '';
        
        courses.forEach(course => {
            const option = document.createElement('option');
            option.value = course.course_code;
            option.textContent = course.course_name;
            courseSelect.appendChild(option);
        });
        
        document.getElementById('addTutorModal').style.display = 'block';
    } catch (error) {
        console.error('获取课程失败:', error);
        alert('获取课程失败，请稍后重试');
    }
};

// 关闭添加助教模态框
window.closeAddTutorModal = function() {
    document.getElementById('addTutorModal').style.display = 'none';
    document.getElementById('studentIdInput').value = '';
};

// 添加助教
window.addTutor = async function() {
    const courseCode = document.getElementById('courseSelect').value;
    const studentId = document.getElementById('studentIdInput').value.trim();
    
    if (!studentId) {
        alert('请输入助教学号');
        return;
    }
        if (studentId>50) {
        alert('学号不能超过50个字');
        return;
    }
    
    try {
        const response = await fetch('/add-tutor', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ courseCode, studentId })
        });
        
        const result = await response.json();
        
        if (response.ok) {
            alert(result.message);
            closeAddTutorModal();
            // 刷新页面
            document.dispatchEvent(new Event('DOMContentLoaded'));
        } else {
            alert(result.message);
        }
    } catch (error) {
        console.error('添加助教失败:', error);
        alert('添加助教失败，请稍后重试');
    }
};

// 移除助教
window.removeTutor = async function(tutorId, button) {
    if (confirm('确定要移除该助教吗？')) {
        try {
            const response = await fetch('/remove-tutor', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ tutorId })
            });
            
            const result = await response.json();
            
            if (response.ok) {
                alert(result.message);
                // 从表格中删除该行
                const row = button.closest('tr');
                row.remove();
                
                // 检查是否还有助教
                const tbody = document.getElementById('tutorsBody');
                if (tbody.children.length === 0) {
                    const newRow = document.createElement('tr');
                    newRow.innerHTML = '<td class="py-3 px-4 text-center" colspan="4">暂无助教</td>';
                    tbody.appendChild(newRow);
                }
            } else {
                alert(result.message);
            }
        } catch (error) {
            console.error('移除助教失败:', error);
            alert('移除助教失败，请稍后重试');
        }
    }
};

document.addEventListener('DOMContentLoaded', function() {
    // 获取"返回"链接元素
    const backLink = document.querySelector('ul.flex li:first-child a');
    if (backLink) {
        // 添加点击事件监听器
        backLink.addEventListener('click', function(event) {
            event.preventDefault(); 
            window.location.href ='success.html'+window.location.search;
        });
    }
});

export{
    renderTutorsTable,
}